import os
import tempfile
from subprocess import call, Popen, DEVNULL
from subprocess import CompletedProcess, run, PIPE, CalledProcessError


def do2(args: str) -> Popen:
    return Popen(args, stdout=DEVNULL, stderr=DEVNULL, shell=True)


def do(args: []) -> CompletedProcess:
    try:
        c = run(args, stdout=PIPE, stderr=PIPE, check=True)
        return c
    except CalledProcessError as e:
        # print(e.returncode)
        print(str(e.stderr, 'utf-8'))
        # report this exception
        ...


def vim_edit(init_msg: str) -> str:
    tf = tempfile.NamedTemporaryFile(suffix=".tmp", delete=False)
    tf.write(bytes(init_msg, encoding='utf-8'))
    tf.close()

    call(['vim', tf.name])

    tf = open(tf.name, 'r')
    edited_str = tf.read()
    tf.close()
    os.unlink(tf.name)
    return edited_str


def combine_path(p: []) -> str:
    raw = '/'.join([i.strip('/') for i in p])
    if p[0][0] == '/':
        raw = '/' + raw
    return raw


from review.models import settings


def get_local_repo(repo: str):
    repo_map = {}
    with open(settings.REPO_MAP_FILE_PATH, 'r') as f:
        lines = f.readlines()

    for line in lines:
        arr = line.split()
        repo_map[arr[0]] = arr[1]
    return repo_map[repo]
